// 安全加密
import Jsencrypt from '@/utils/jsencrypt.js'; // RSA加密
import CryptoJS from 'crypto-js'; // AES加密

//RSA公钥
let publicKey =
  '-----BEGIN PUBLIC KEY-----' + // 必须添加，切记
  process.env.VUE_APP_PUBLICKEY + // 此处使用后端给的公钥
  '-----END PUBLIC KEY-----'; // 必须添加，切记

// msg 类型为 string 字符串，不能搞错类型，不然生成之后的内容后端会解密失败
export const rsaEncrypt = (msg) => {
  const JsRsa = new Jsencrypt();
  JsRsa.setPublicKey(publicKey);
  return JsRsa.encrypt(msg);
};

//AES加密
//keyStr是加密密钥，每次发送数据，加密的密钥都需要不同。
let ivStr = 'K2Gc3g1Hik38k9Zi'; //矢量
//加密
export function aes_encrypt(data, keyStr) {
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  var iv = CryptoJS.enc.Utf8.parse(ivStr);
  var encrypted = CryptoJS.AES.encrypt(data, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });
  return encrypted.toString();
}

//解密
export function aes_decrypt(data, keyStr) {
  //console.log(keyStr);
  var key = CryptoJS.enc.Utf8.parse(keyStr);
  var iv = CryptoJS.enc.Utf8.parse(ivStr);
  var restoreBase64 = data.replace(/[\r\n]/g, '');
  var decrypt = CryptoJS.AES.decrypt(restoreBase64, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

//签名算法
export function getSign(obj) {
  var keys = Object.keys(obj).sort();
  var newObj = {};
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var value = obj[key];
    //console.log(value);
    if (typeof value === 'string') {
      newObj[key] =
        Object.prototype.toString.call(value) === '[object Object]'
          ? getSign(value.trim())
          : value.trim();
    } else {
      newObj[key] =
        Object.prototype.toString.call(value) === '[object Object]'
          ? getSign(value)
          : value;
    }
  }
  return newObj;
}

//传参加密
export function paramsEncrypt(obj, aesKey) {
  var keys = Object.keys(obj).sort();
  var newObj = {};
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var value = obj[key];
    if (typeof value === 'string') {
      newObj[key] =
        Object.prototype.toString.call(value) === '[object Object]'
          ? paramsEncrypt(value.trim(), aesKey)
          : aes_encrypt(value.trim(), aesKey);
    } else {
      newObj[key] =
        Object.prototype.toString.call(value) === '[object Object]'
          ? paramsEncrypt(value, aesKey)
          : aes_encrypt(value, aesKey);
    }
  }
  return newObj;
}
